package com.servlet;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class SendRequestServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String method = req.getParameter("method");
        String url = req.getParameter("url");

        HttpRequest httpRequest = HttpUtil.createGet(url);

        if("POST".equals(method)){
            httpRequest = HttpUtil.createPost(url);
            String body = req.getParameter("body");
            if(validaParamAreValid(body)){
                httpRequest.body(body);
            }
        }
        String responseBody = httpRequest.addHeaders((Map<String,String>)getParameter(req,"headers"))
                .form((Map<String,Object>)getParameter(req,"params"))
                .header("Content-Type", "application/json;charset=utf-8")//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute().body();

        resp.setContentType("application/json;charset=utf-8");
        resp.setStatus(200);
        resp.getWriter().write(responseBody);

    }

    boolean validaParamAreValid(String param){
        return param != null && !"".equals(param) && !"=".equals(param) && param.length() > 2;
    }

    Object getParameter(HttpServletRequest req, String key){
        Map<String,Object> headersMap = null;
        String headers = req.getParameter(key);

        if(validaParamAreValid(headers)){
            headersMap = new HashMap<>(16);
            for (String header : headers.split("&")) {
                String[] split = header.split("=");
                if(split.length > 1){
                    headersMap.put(split[0],split[1]);
                }
            }
        }
        return headersMap;
    }

}
